<template>
  <div class="success-container">
    <div class="decorative-strip"></div>
    <a-card class="success-card">
      <div v-if="loading" class="loading-state">
        <a-spin />
        <p>Loading payment status...</p>
      </div>
      <div class="success-header" v-else>
        <div class="success-icon" v-if="payStatus === 'succeeded'">
          <check-circle-outlined />
        </div>
        <div class="failed-icon" v-else>
          <ExclamationCircleOutlined />
        </div>
        <p class="subtitle">{{ getPaymentStatusMessage() }}</p>
      </div>

      <div class="info-section">
        <div v-if="orderLoading" class="order-loading">
          <a-spin :indicator="spinnerIndicator" />
          <p>Loading...</p>
        </div>
        <template v-else>
          <div class="info-row">
            <span class="label">Order Number：</span>
            <span class="value">{{ orderNo }}</span>
          </div>
          <a-divider dashed />

          <div class="info-row">
            <span class="label">Payment amount：</span>
            <span class="value highlight">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(amount) }}</span>
          </div>
          <a-divider dashed />

          <div class="info-row">
            <span class="label">Payment Time：</span>
            <span class="value"><DateFormatter :value="payTime" format="MM/DD/YYYY HH:mm:ss" fallback="No" /></span>
          </div>
        </template>
      </div>

      <div class="action-btns">
        <a-button
            type="primary"
            class="black-btn"
            @click="viewOrder">
          View order details
        </a-button>
        <a-button
            class="ghost-btn"
            @click="goHome">
          Back to Home
        </a-button>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance, h} from 'vue';
import { useRouter } from 'vue-router';
import { CheckCircleOutlined, ExclamationCircleOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import {getOrderDetail} from "@/api/order.ts";
import {Local, Session} from "@/utils/storage.ts";
import {useCurrencyStore} from '@/store/currency.ts'
import DateFormatter from "@/components/common/DateFormatter.vue";
import {message} from "ant-design-vue";
// 从Stripe库中导入loadStripe函数，用于加载Stripe对象
import { loadStripe } from "@stripe/stripe-js";
import {getSetting} from "@/api/help.ts";

const { proxy } = getCurrentInstance();
const useCurrency = useCurrencyStore();
const router = useRouter();
const loading = ref(true);
const orderLoading = ref(true);

// 自定义黑色加载图标
const spinnerIndicator = h(LoadingOutlined, { style: 'font-size: 24px; color: #000;' });

// 订单数据
const orderNo = ref(0);
const amount = ref(0);
const payTime = ref('');
const orderId = ref('');
const status = ref('');

// 声明一个变量stripe，用于存储Stripe对象
let stripe;
// 定义一个响应式变量messages，用于存储消息
const messages = ref([]);
const payStatus = ref(null);
// 定义一个响应式变量clientSecret，用于存储支付意图的客户端密钥
const clientSecret = ref('');
const siteKey = ref('');

// 根据支付状态返回对应的消息
const getPaymentStatusMessage = () => {
  switch(payStatus.value) {
    case 'succeeded':
      return 'Payment Successful';
    case 'processing':
      return 'Payment processing. We\'ll update you when payment is received.';
    case 'requires_payment_method':
      return 'Payment failed. Please try another payment method.';
    default:
      return 'Something went wrong.';
  }
};

// 模拟加载
onMounted(async () => {
  // 先获取 siteKey，确保有值
  await getSiteKey();

  // 确保 siteKey.value 有值
  if (!siteKey.value) {
    message.error('Unable to obtain payment key');
    loading.value = false;
    return;
  }

  // 使用publishableKey加载Stripe对象
  stripe = await loadStripe(siteKey.value);

  // 从 Session 中获取 clientSecret
  clientSecret.value = Session.get('clientSecret');

  // 确保 clientSecret.value 有值
  if (!clientSecret.value) {
    // 尝试从 URL 参数获取
    const urlParams = new URLSearchParams(window.location.search);
    clientSecret.value = urlParams.get('payment_intent_client_secret');

    if (!clientSecret.value) {
      message.error('Unable to obtain payment information');
      loading.value = false;
      return;
    }
  }

  // 使用Stripe对象的retrievePaymentIntent方法获取支付意图信息
  const {error, paymentIntent} = await stripe.retrievePaymentIntent(
      clientSecret.value,
  );

  // 如果获取支付意图时发生错误，将错误信息推入messages数组
  if (error) {
    messages.value.push(error.message);
  }
  // 将支付意图的状态和ID信息推入messages数组
  messages.value.push(`Payment ${paymentIntent.status}: ${paymentIntent.id}`)

  payStatus.value = paymentIntent.status

  loading.value = false;
  await getOrderDetails();
});

const getOrderDetails = async () => {
  orderLoading.value = true;
  const res = await getOrderDetail(Local.get('orderId'))

  console.log('Order Detail:', res)
  if (res.code === 200) {
    orderNo.value = res.result.order_no
    amount.value = res.result.pay_price
    payTime.value = res.result.pay_time
    status.value = res.result.status
    orderId.value = res.result.id
  }else {
    message.error(res.msg || 'Failed to get order details')
  }
  orderLoading.value = false;
}

const getSiteKey = async () => {
  try {
    if (Local.get('settingConfig') && Local.get('settingConfig').stripe_pay_key) {
      siteKey.value = Local.get('settingConfig').stripe_pay_key;
      return;
    }

    const res = await getSetting();
    if (res.code === 200 && res.result && res.result.stripe_pay_key) {
      siteKey.value = res.result.stripe_pay_key;
      Local.set('settingConfig', res.result);
    } else {
      console.error('Failed to obtain payment key:', res);
    }
  } catch (error) {
    console.error('Failed to obtain payment key:', error);
  }
}

const viewOrder = () => {
  router.push('/user/orders');
};

const goHome = () => {
  router.push('/');
};
</script>

<style lang="scss" scoped>
.success-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  padding: 40px 20px;
  position: relative;

  .page-title {
    text-align: center;
    font-size: 36px;
    color: #333;
    margin-bottom: 40px;
  }

  .decorative-strip {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 8px;
    background: repeating-linear-gradient(
            45deg,
            #000,
            #000 15px,
            transparent 15px,
            transparent 30px
    );
  }
}

.success-card {
  max-width: 680px;
  margin: 0 auto;
  border: 2px solid #000;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);

  :deep(.ant-card-body) {
    padding: 40px;
  }
}

.success-header {
  text-align: center;
  margin-bottom: 40px;

  .success-icon {
    font-size: 60px;
    color: #52c41a;
    animation: checkmark 0.6s ease;
  }

  .failed-icon {
    font-size: 60px;
    color: #d41818;
    animation: checkmark 0.6s ease;
  }

  .title {
    font-size: 32px;
    color: #333;
    margin: 20px 0 8px;
    font-weight: 500;
  }

  .subtitle {
    font-size: 16px;
    color: #666;
    letter-spacing: 2px;
  }
}

.loading-state {
  text-align: center;
  margin: 40px 0;
}

.info-section {
  margin: 30px 0;

  .order-loading {
    text-align: center;
    padding: 30px 0;

    p {
      margin-top: 10px;
      color: #333;
    }
  }

  .info-row {
    display: flex;
    justify-content: space-between;
    padding: 18px 0;

    .label {
      color: #666;
      font-size: 16px;
    }

    .value {
      color: #333;
      font-weight: 500;

      &.highlight {
        font-size: 24px;
        letter-spacing: 1px;
      }
    }
  }
}

.action-btns {
  text-align: center;

  .black-btn {
    background: #000;
    border-color: #000;
    font-size: 16px;

    &:hover {
      background: #333;
    }
  }

  .ghost-btn {
    border-color: #000;
    color: #000;
    margin-left: 20px;

    &:hover {
      background: rgba(0,0,0,0.05);
    }
  }
}

@keyframes checkmark {
  0% { transform: scale(0); opacity: 0; }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); opacity: 1; }
}
</style>
